import jwt
import datetime


class ToolJwt:
    # 生成token
    # 参数user为一个字典{id，username
    def get_token(self,user):
        # 头部信息
        header = {
            'alg': 'HS256',  # 加密算法
            'typ': 'JWT'  # token类型
        }
        # 秘钥,应保持安全，不泄露
        SECRET_KEY = 'secret'

        # 载荷信息
        payload = {
            'userid': user.get('id'),
            'username': user.get('name'),
            'exp': datetime.datetime.now()+ datetime.timedelta(hours=2)  # 过期时间
        }
        # 生成token
        token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
        return token

    # 验证token
    def check_token(self,token):
        # 秘钥,应保持安全，不泄露
        SECRET_KEY = 'secret'
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
            return payload
        except jwt.ExpiredSignatureError:
            return 'token过期'
        except jwt.InvalidTokenError:
            return '无效token'


tool=ToolJwt()
print(tool.get_token({'id':1,'name':'admin'}))
# token3='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3MzAzNzYwOTl9.zn3su2BO8pLOVrVuplGZDy9MrgL6FhHEVuIqZ9l0yuo'
# token='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3MzAzMDYxNjR9.ys2FXUMNeq2VcBQtPcVl3pRO-JJng5s9OnJQDRhLQIA'
# token2='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3MzAzMTE1NTR9.p2k3Mehplv3LiK33fqGHsMvXsw3axf1jG-bHPaWryug'
# print(tool.check_token(token))
# print(tool.check_token(token2))